import React, {useState, useEffect} from 'react';
import Checkbox from "../../../components/general/Checkbox"

const EventFilterCheckbox = props => {
  let userFilterData = props.userFilterData.length ? props.userFilterData.split(',') : [];
  const [checked, setChecked] = useState(userFilterData.includes(props.data.id.toString()))

  useEffect(() => {
    setChecked(userFilterData.includes(props.data.id.toString()))
  }, [userFilterData])

  const toggleCheckboxChange = (e) => {
    setChecked(!checked)
    userFilterData = props.userFilterData.length ? props.userFilterData.split(',') : [];
    const index = userFilterData.indexOf(e.target.value);
    index === -1 ? userFilterData.push(e.target.value) : userFilterData.splice(index, 1)
    props.setChecked(props.typeCheck, props.typeFilter, userFilterData.join());
  }

  return (
    <Checkbox
      value={props.data.id}
      name={`${props.typeFilter}${props.data.id}`}
      checked={checked}
      onChange={toggleCheckboxChange}
      label={props.data.name}
      className="event-filter__item"
      labelClassName="event-filter__checkbox-label"
      iconClassName="event-filter__checkbox-icon"
    />
  )
}

export default EventFilterCheckbox;
